import type { App } from 'vue';
interface ViewportDirectiveBinding {
  callback: () => void;
  once?: boolean;
  threshold?: number;
}

declare global {
  interface HTMLElement {
    _viewportObserver?: IntersectionObserver;
  }
}

export default {
  install(app: App) {
    // 添加一个全局方法
    // app.config.globalProperties.$myMethod = () => {
    //   console.log('This is a global method added by MyPlugin');
    // };

    app.directive('lazy', {
      // 当元素挂载时
      mounted(el: HTMLElement, binding: { value: string }) {
        const img = el as HTMLImageElement;
        img.src = '';
        const observer = new IntersectionObserver(
          (entries) => {
            entries.forEach((entry) => {
              if (entry.isIntersecting) {
                img.src = binding.value;
                observer.unobserve(el);
              }
            });
          },
          {
            threshold: 0.1 // 图片在视口出现的阈值，表示 10% 进入视口时开始加载
          }
        );

        observer.observe(el); // 开始观察图片元素
        el._lazyObserver = observer; // 保存观察器
      },
      unmounted(el) {
        // 在元素销毁时移除观察器
        if (el._lazyObserver) {
          el._lazyObserver.disconnect();
          delete el._lazyObserver;
        }
      }
    });

    // 添加一个全局指令
    app.directive('viewport', {
      mounted(el: HTMLElement, binding: { value: ViewportDirectiveBinding }) {
        const { callback, once = true, threshold = 0.1 } = binding.value;
        if (threshold < 0 || threshold > 1) {
          throw new Error('v-viewport: threshold should be between 0 and 1');
        }
        const observer = new IntersectionObserver(
          (entries) => {
            entries.forEach((entry) => {
              if (entry.isIntersecting) {
                callback();
                if (once) {
                  observer.unobserve(el);
                }
              }
            });
          },
          {
            threshold // 使用传入的阈值
          }
        );

        observer.observe(el);
        el._viewportObserver = observer;
      },
      unmounted(el) {
        if (el._viewportObserver) {
          el._viewportObserver.disconnect();
          delete el._viewportObserver;
        }
      }
    });

    // 添加一个全局混入
    // app.mixin({
    //   created() {
    //     console.log('MyPlugin mixin created hook');
    //   }
    // });

    // 添加一个全局组件
    // app.component('MyComponent', {
    //   template: '<div>My Custom Component</div>'
    // });
  }
};
